//
//  emoticonLayout.swift
//  customKeyboard
//
//  Created by changhongliang on 2017/8/21.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit

class emoticonLayout: UICollectionViewLayout {
    //1.Configurable properties
    var numberOfColumns = 7
    var numberOfRows = 3
    var cellPadding:CGFloat = 0
    let screenWidth = UIScreen.main.bounds.size.width
    let screenHeight = UIScreen.main.bounds.size.height
    var currentPage = 0
    
    //2.Array to keep a cache of attributes
    private var cache = [UICollectionViewLayoutAttributes]()
    
    override func prepare() {
//        if cache.isEmpty {
            for section in 0 ..< collectionView!.numberOfSections{
                let sectonItems = collectionView!.numberOfItems(inSection: section)
                for item in 0 ..< sectonItems {
                    let indexPath = IndexPath(item: item, section: section)
                    let pageNumber = item / (numberOfRows * numberOfColumns)
                    let leftNumber = item % (numberOfRows * numberOfColumns)
                    let width = screenWidth / CGFloat(numberOfColumns)
                    let x = CGFloat(pageNumber + currentPage) * screenWidth + CGFloat(leftNumber % numberOfColumns) * width
                    let y = CGFloat(leftNumber / numberOfColumns) * width
                    let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                    let frame = CGRect(x: x, y: y, width: width, height:width)
                    let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
                    attributes.frame = insetFrame
                    cache.append(attributes)
                }
                 currentPage += sectonItems/(numberOfRows * numberOfColumns)
            }
//        }
        
    }
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: CGFloat(currentPage) * screenWidth, height:0.0)
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var layoutAttributes = [UICollectionViewLayoutAttributes]()
        
                // Loop through the cache and look for items in the rect
                for attributes  in cache {
                    if attributes.frame.intersects(rect ) {
                        layoutAttributes.append(attributes)
                    }
                }
                return layoutAttributes
    }
    
}
